<?php


namespace app\web\controller;

use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlCouponActive;
use app\common\cachemodel\ZlCouponActiveGiveRecord;
use app\common\lib\exception\ApiException;
use app\common\lib\Jssdk;
use app\common\lib\Util;
use think\Controller;
use think\Env;
use think\Exception;
use XznsTools\cache\CacheManage;

class YearActiv2021 extends Controller
{
    protected $year = 2021;
    protected $shareTitle = '新春领好运！';
    protected $descript = '优惠福利等你来拿！';

    /**
     *
     */
    public function index()
    {
        $height = input('h/d', 0);
        $dd = input('dd/d', 0);
        $headers = $this->request->header();
        $isUpdate = 0;
        $isUpdate2 = 1;
        if (isset($headers['access-token'], $headers['app-type'], $headers['sign']))
        {
            //校验token
            try
            {
                if (in_array($headers['version'], ['1.9.4', '1.9.5',]))
                {
                    $isUpdate = 1;
                }
                $auth = new Auth();
                $auth->checkRequestAuth();
                $userInfo = $auth->user;
                if (Util::CheckAppVersion('2.5.2') !== '小')
                {
                    $isUpdate2 = 0;
                }
            }
            catch (Exception $e)
            {
                throw new ApiException('2021年活动异常' . $e->getMessage());
            }
            $uid = (int)$userInfo['id'];

        } else
        {
            $uid = 0;
            $signPackage = (new Jssdk())->getSignPackage();

            $giveRecord = $this->getGiveRecord();

            return $this->fetch('year_activ/share_index', [
                'domain' => Env::get('host.domain'),
                'record' => $giveRecord,
                'recordLen' => count($giveRecord),
                'signPackage' => $signPackage,
                'oss' => Env::get('host.photo'),
                'shareTitle' => $this->shareTitle,
                'descript' => $this->descript,
                'uid' => $uid,
                'height' => $height,
                'is_show_nav' => true
            ]);
        }

        $time = Util::testGetTime('2021');

        $d = (int)date('Ymd', $time);

        if ($d === 20210212 && $time < 1613066400)
        {
            $d = 20210211;
        }

        $data = [
            11 => [
                'day' => 20210211,
                'a1_max' => 5000,
                'a1_time' => 1613001600, // 活动开始时间戳 2021-02-11 08:00:00
                'a1_id' => 15, // 优惠券活动ID
                'a2_max' => 20,
                'a2_time' => 1613059200, // 活动开始时间戳 2021-02-12 00:00:00
                'a2_id' => 35, // 优惠券组号
            ],
            12 => [
                'day' => 20210212,
                'a1_max' => 5000,
                'a1_time' => 1613088000, // 活动开始时间戳 2021-02-12 08:00:00
                'a1_id' => 16, // 优惠券活动ID
                'a2_max' => 25,
                'a2_time' => 1613102400, // 活动开始时间戳 2021-02-12 12:00:00
                'a2_id' => 36, // 优惠券组号
            ],
            13 => [
                'day' => 20210213,
                'a1_max' => 5000,
                'a1_time' => 1613174400, // 活动开始时间戳 2021-02-13 08:00:00
                'a1_id' => 17, // 优惠券活动ID
                'a2_max' => 30,
                'a2_time' => 1613188800, // 活动开始时间戳 2021-02-13 12:00:00
                'a2_id' => 37, // 优惠券组号
            ],
            14 => [
                'day' => 20210214,
                'a1_max' => 3000,
                'a1_time' => 1613260800, // 活动开始时间戳 2021-02-14 08:00:00
                'a1_id' => 18, // 优惠券活动ID
                'a2_max' => 30,
                'a2_time' => 1613275200, // 活动开始时间戳 2021-02-14 12:00:00
                'a2_id' => 38, // 优惠券组号
            ],
            15 => [
                'day' => 20210215,
                'a1_max' => 5000,
                'a1_time' => 1613347200, // 活动开始时间戳 2021-02-15 08:00:00
                'a1_id' => 19, // 优惠券活动ID
                'a2_max' => 35,
                'a2_time' => 1613361600, // 活动开始时间戳 2021-02-15 12:00:00
                'a2_id' => 41, // 优惠券组号
            ],
            16 => [
                'day' => 20210216,
                'a1_max' => 3000,
                'a1_time' => 1613433600, // 活动开始时间戳 2021-02-16 08:00:00
                'a1_id' => 20, // 优惠券活动ID
                'a2_max' => 35,
                'a2_time' => 1613448000, // 活动开始时间戳 2021-02-16 12:00:00
                'a2_id' => 40, // 优惠券组号
            ],
            17 => [
                'day' => 20210217,
                'a1_max' => 5000,
                'a1_time' => 1613520000, // 活动开始时间戳 2021-02-17 08:00:00
                'a1_id' => 21, // 优惠券活动ID
                'a2_max' => 40,
                'a2_time' => 1613534400, // 活动开始时间戳 2021-02-17 12:00:00
                'a2_id' => 39, // 优惠券组号
            ],
        ];

        $activGiveInfo1 = (new ZlCouponActive())->getActiveInfo();
        $getNum = $this->getGiveNum();
        $resData = [];
        $index = 11;
        $couponActiveGiveRecordModel = new ZlCouponActiveGiveRecord();
        foreach ($data as $key => $val)
        {
            $giveNum = $couponActiveGiveRecordModel->getActiveGiveNum($uid, $val['a1_id']);
            if ($d > $val['day'])
            { // 活动已过期
                $b1_status = 4;
                $b1_name = '已抢空';
                if ($uid && $giveNum > 0)
                {
                    $b1_status = 5;
                    $b1_name = '已领取';
                }

                $b2_status = 4;
                $b2_name = '已抢空';
                if ($uid)
                {
                    $giveUid = $this->getGiveUid($val['a2_id']);
                    if (in_array($uid, $giveUid))
                    {   // 已领取
                        $b2_status = 5;
                        $b2_name = '已领取';
                    }
                }
                $resData[$key] = [
                    'status' => 3, // 已结束
                    'a1_num' => 0,
                    'a1_time' => -1,
                    'num1' => $giveNum,
                    'b1_status' => $b1_status, // 按钮状态
                    'b1_name' => $b1_name,
                    'a2_num' => $val['a2_max'],
                    'a2_time' => -1,
                    'b2_status' => $b2_status,   // 按钮状态
                    'b2_name' => $b2_name,
                ];
            }

            if ($d === $val['day'])
            { // 活动进行中
                $index = $key;
                $time1 = $val['a1_time'] > $time ? $val['a1_time'] - $time : 0;
                $time2 = $val['a2_time'] > $time ? $val['a2_time'] - $time : 0;
                $num1 = $val['a1_max'] - $activGiveInfo1[$val['a1_id']]['send_num'];
                $b1_status = 3;
                $b1_name = '立即抢';
                if ($time1 > 0)
                {
                    $b1_status = 2;
                    $b1_name = '即将开抢';
                } else
                {
                    // 优惠券自动递减逻辑
                    // $hour = date('H');
                    // $min = date('i');
                    // // 优惠卷递减领取数量基数
                    // $baseNum = (int)(((($hour - 12) * 3600 + $min * 60) / 300) * 19);
                    //
                    // $num1 -= $baseNum;
                }

                switch (true)
                {
                    case $d === 20210211 && $time >= 1613052960: // 2021-02-11 22:16:00
                    case $d === 20210212 && $time >= 1613115720: // 2021-02-12 15:42:00
                    case $d === 20210213 && $time >= 1613205360: // 2021-02-13 16:36:00
                    case $d === 20210214 && $time >= 1613297880: // 2021-02-14 18:18:00
                    case $d === 20210215 && $time >= 1613378220: // 2021-02-15 16:37:00
                    case $d === 20210216 && $time >= 1613459880: // 2021-02-16 15:18:00
                    case $d === 20210217 && $time >= 1613555640: // 2021-02-17 17:54:00
                        $num1 = 0;
                        break;
                    default:
                }

                if ($num1 <= 0)
                {
                    $num1 = 0;
                    $b1_status = 6;
                    $b1_name = '已抢空';
                }

                if ($uid && $giveNum > 0)
                {
                    if ($giveNum < $activGiveInfo1[$val['a1_id']]['c_num'])
                    {
                        $b1_status = 8;
                        $b1_name = '分享再抢一次';
                    } else
                    {
                        $b1_status = 5;
                        $b1_name = '已领取';
                    }
                }
                $num = $val['a2_max'] - ($getNum[$val['a2_id']] ?? 0);
                $num = $num > 0 ? $num : 0;
                $b2_status = 7;
                $b2_name = '分享后可抢';

                if ($num <= 0)
                {
                    $b2_status = 6;
                    $b2_name = '已抢空';
                }
                if ($uid)
                {
                    $giveUid = $this->getGiveUid($val['a2_id']);
                    if (in_array($uid, $giveUid))
                    {   // 已领取
                        $b2_status = 5;
                        $b2_name = '已领取';
                    }
                }

                $resData[$key] = [
                    'status' => 2, // 进行中
                    'a1_num' => $num1,
                    'a1_time' => $time1,
                    // 'a1_time' => 30,
                    'num1' => $giveNum,
                    'b1_status' => $b1_status, // 按钮状态
                    'b1_name' => $b1_name,
                    'a2_num' => $val['a2_max'],
                    'a2_time' => $time2,
                    // 'a2_time' => 40,
                    'b2_status' => $b2_status,   // 按钮状态
                    'b2_name' => $b2_name,
                ];
            }

            if ($d < $val['day'])
            { // 活动未开始
                $resData[$key] = [
                    'status' => 1, // 未开始
                    'a1_num' => $val['a1_max'],
                    'a1_time' => -1,
                    'num1' => 0,
                    'b1_status' => 1,
                    'b1_name' => '即将开抢',
                    'a2_num' => $val['a2_max'],
                    'a2_time' => -1,
                    'b2_status' => 1,
                    'b2_name' => '即将开抢',
                ];
            }
        }

        $headersStr = '[]';
        if ($uid)
        {
            unset($headers['cookie'], $headers['time'], $headers['content-type'], $headers['content-length']);
            $headersStr = json_encode($headers);
        }

        $signPackage = (new Jssdk())->getSignPackage();

        $giveRecord = $this->getGiveRecord();

        return $this->fetch('year_activ/index', [
            'data' => $resData,
            'index' => $dd ?: $index,
            'domain' => Env::get('host.domain'),
            'record' => $giveRecord,
            'recordLen' => count($giveRecord),
            'signPackage' => $signPackage,
            'headers' => $headersStr,
            'appType' => $headers['app-type'] ?? '',
            'isUpdate' => $isUpdate,
            'isUpdate2' => $isUpdate2,
            'oss' => Env::get('host.photo'),
            'login' => $uid ? 1 : 0,
            'shareTitle' => $this->shareTitle,
            'descript' => $this->descript,
            'uid' => $uid,
            'height' => $height,
            'is_show_nav' => true
        ]);
    }

    /**
     * 获取活动优惠券领取数量 抢
     */
    private function getGiveNum()
    {
        $redis = CacheManage::getInstance()->redisHandler;

        $data = $redis->hGetAll('year' . $this->year . ':activ_send_num');

        return $data;
    }

    /**
     * 获取活动优惠券领取的用户 抢
     */
    private function getGiveUid($id)
    {
        $redis = CacheManage::getInstance()->redisHandler;

        $giveData = $redis->lRange('year' . $this->year . ':activ_send_uid:' . $id, 0, -1);

        return $giveData ?: [];
    }

    private function getGiveInfo1($uid)
    {
        $couponActiveGiveRecordModel = new ZlCouponActiveGiveRecord();
        $giveRecordData = $couponActiveGiveRecordModel->getGiveRecord($uid);
        $giveRecordDataIds = empty($giveRecordData) ? [] : array_keys($giveRecordData);
        return $giveRecordDataIds;
    }

    private function getGiveRecord()
    {
        $redis = CacheManage::getInstance()->redisHandler;

        $giveData = $redis->lRange('year' . $this->year . ':give:info', 0, -1);

        $giveData = $giveData ?: [];

        $i = [
            1 => [ // 限量 3000
                15 => '一生报告8折券',// 20210211
                16 => '年度运势8折券',// 20210212
                17 => '月运解锁8折券',// 20210213
                18 => '合盘报告8折券',// 20210214
                19 => '日运全年8折券',// 20210215
                20 => '幸运之城8折券',// 20210216
                21 => '会员解锁8折券',// 20210217
            ],
            2 => [
                35 => '一生报告免费券',// 20210211
                36 => '年度运势免费券',// 20210212
                37 => '单月运势免费券',// 20210213
                38 => '合盘报告免费券',// 20210214
                41 => '日运全年年费券',// 20210215
                40 => '幸运之城免费券',// 20210216
                39 => '会员解锁免费券',// 20210217
            ]
        ];

        $data = [];
        foreach ($giveData as $value)
        {
            $d = json_decode($value, true);

            $d['avatar'] = $d['avatar'] ? Env::get('host.photo') . $d['avatar'] : '/static/new_year_activ/img/avatar.png';

            $d['cname'] = $i[$d['type']][$d['id']] ?? '';

            if ($d['cname'])
            {
                $data[] = $d;
            }
        }
        return $data;
    }
}
